package com.example.yichuangyun.mvvm.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;

import com.dylanc.viewbinding.ViewBindingUtil;
import com.example.yichuangyun.R;
import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.dialog.LoadingDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.PushModel;
import com.example.yichuangyun.mvvm.di.ActivityComponent;
import com.example.yichuangyun.mvvm.di.ActivityModule;
import com.example.yichuangyun.mvvm.di.DaggerActivityComponent;
import com.example.yichuangyun.mvvm.di.retrofit.RetrofitHelper;
import com.example.yichuangyun.utils.ActivityStackManager;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ScreenUtil;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.igexin.sdk.PushManager;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

import javax.inject.Inject;

public abstract class BaseActivity<T extends ViewDataBinding, D extends BaseViewModel> extends FragmentActivity {

    protected T binding;
    protected D viewModel;
    protected Context context;
    protected TextView tvMainTitle;
    protected TextView tvRight;
    protected ImageView ivRight;
    protected ImageView ivBack;
    private RelativeLayout rootLayout;
    private LoadingDialog loadingDialog;
    @Inject
    RetrofitHelper retrofitHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 添加Activity到堆栈
        MyApplication.getInstance().addActivity(this);
        // 我们建议开发者在 Application.onCreate() 和主 Activity.onCreate() 方法中初始化个推 SDK。多次调用 SDK 初始化并无影响。
        PushManager.getInstance().initialize(context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = ViewBindingUtil.inflateWithGeneric(this, getLayoutInflater());
        setContentView(binding.getRoot());
        binding.setLifecycleOwner(this);
        context = this;
        EventBus.getDefault().register(this);
        requestTranslucentStatusBar(true);
        initLoadingDialog();
        initInject();
        viewModel = bindModel();
        viewModel.setRetrofitHelper(retrofitHelper);
        initData();
        initCtrl();
        initClick();
    }

    protected abstract D bindModel();

    protected abstract void initInject();

    protected abstract void initData();

    protected void initCtrl() {

    }

    protected void initClick() {
    }

    protected void setRightText(String rightText, int colorId) {
        if (tvRight != null) {
            tvRight.setText(rightText);
            tvRight.setTextColor(ContextCompat.getColor(this, colorId));
            tvRight.setVisibility(View.VISIBLE);
        }
    }

    protected void setRightResource(int resourceId) {
        if (ivRight != null) {
            ivRight.setImageResource(resourceId);
            ivRight.setVisibility(View.VISIBLE);
        }
    }

    protected ActivityComponent getActivityComponent() {
        return DaggerActivityComponent.builder()
                .appComponent(MyApplication.getInstance().getAppComponent())
                .activityModule(new ActivityModule(this))
                .build();
    }

//    protected AppComponent getAppComponent() {
//        return MyApplication.getInstance().getAppComponent();
//    }

    public <T extends BaseViewModel> T getViewModel(FragmentActivity activity, Class<T> cls) {
        return new ViewModelProvider(activity).get(cls);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    /**
     * 设置标题
     *
     * @param title 标题（返回键关闭当前页）
     */
    protected void initTitleBar(String title) {
        initTitleView();
        tvMainTitle.setText(title);
    }

    protected void initTitleBar(String title, boolean isShowLeftImg) {
        ivBack.setVisibility(isShowLeftImg ? View.VISIBLE : View.GONE);
        tvMainTitle.setText(title);
    }

    protected void initTitleBar() {
        initTitleView();
    }

    /**
     * 设置标题
     *
     * @param title 标题（返回键关闭当前页）
     */
    protected void initTitleBar(String title, int backColor) {
        tvMainTitle.setText(title);
        rootLayout.setBackgroundResource(backColor);
    }

    /**
     * 设置标题和监听
     *
     * @param title    设置标题
     * @param listener 设置返回键 响应事件
     */
    protected void initTitleBar(String title, View.OnClickListener listener) {
        ivBack.setOnClickListener(listener);
        tvMainTitle.setText(title);
    }

    private void initTitleView() {
        rootLayout = findViewById(R.id.rl_main_title);
        rootLayout.setPadding(0, ScreenUtil.getStatusBarHeight(context), 0, 0);
        tvMainTitle = findViewById(R.id.tv_main_title);
        tvRight = findViewById(R.id.tv_right);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(v -> finish());
    }

    /**
     * 设置标题栏右侧标题和监听
     *
     * @param title    设置右侧文字
     * @param listener 设置返回键 响应事件
     */
    protected void setRightTextBar(String title, View.OnClickListener listener) {
        tvRight = findViewById(R.id.tv_right);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText(title);
        tvRight.setOnClickListener(listener);
    }

    /**
     * 设置标题栏右侧标题
     *
     * @param title 右侧文字
     */
    protected void setRightText(String title) {
        if (tvRight != null) {
            tvRight.setVisibility(View.VISIBLE);
        } else {
            tvRight = findViewById(R.id.tv_right);
        }
        tvRight.setText(title);
    }

    /**
     * 设置标题栏右侧图片和可见性
     *
     * @param imageResource 图片
     */
    protected void setRightImage(int imageResource) {
        if (ivRight == null) {
            ivRight = findViewById(R.id.iv_right);
        }
        ivRight.setImageResource(imageResource);
    }

    /**
     * 设置标题栏左侧图片和可见性
     *
     * @param imageResource 图片
     */
    protected void setLeftImage(int imageResource) {
        if (ivBack != null) {
            ivBack.setImageResource(imageResource);
        } else {
            ivBack = findViewById(R.id.iv_back);
            ivBack.setImageResource(imageResource);
        }
    }

    protected void setLineGone() {
        View line = findViewById(R.id.line);
        line.setVisibility(View.GONE);
    }

    /**
     * 设置透明状态栏（API21，5.0之后才能用）
     *
     * @param isLightMode 是否为亮色模式（黑色字体，需要6.0 以后支持，否则显示无效）
     */
    protected void requestTranslucentStatusBar(boolean isLightMode) {
        //大于6.0 并且是亮色模式
        if (isLightMode) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        } else {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
        getWindow().setStatusBarColor(Color.TRANSPARENT);
    }

    public void initLoadingDialog() {
        if (null == loadingDialog) {
            LoadingDialog.Builder builder = new LoadingDialog.Builder(this)
                    .setCancelOutside(false)
                    .setCancelable(false);
            loadingDialog = builder.create();
        }
    }

    public void showLoadingDialog() {
        if (null != loadingDialog) {
            loadingDialog.show();
        }
    }

    public void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(PushModel pushModel) {
        if (null != pushModel) {
            String mTelNumber = pushModel.getMobile();
            if (!XXPermissions.isGrantedPermission(context, Permission.CALL_PHONE)) {
                XXPermissions.with(context)
                        .permission(Permission.CALL_PHONE)
                        .request((permissions, all) -> {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_CALL);
                            intent.setData(Uri.parse("tel:" + mTelNumber));
                            startActivity(intent);
                        });
            } else {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + mTelNumber));
                startActivity(intent);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (eventBusModel.getMsg().equals(Constant.logout)) {
            CommonUtil.jumpToLogin(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStackManager.getInstance().popActivity(this);
        if (binding != null) {
            binding.unbind();
        }
        if (viewModel != null) {
            viewModel.unSubscribe();
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        EventBus.getDefault().unregister(this);
    }
}
